package com.balloon.gateway.converter;

import com.balloon.gateway.security.manager.TokenAuthenticationManager;
import com.balloon.gateway.security.user.entity.SystemUser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.server.RequestPath;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liaofuxing
 * @version 1.0.0
 * @date 2022/3/8 11:12
 * @description JsonBody消息转换器
 */
@Component
public class JsonBodyAuthConverter implements ServerAuthenticationConverter {

    @Resource
    private TokenAuthenticationManager tokenAuthenticationManager;

    @Override
    public Mono<Authentication> convert(ServerWebExchange exchange) {

        return exchange
                .getRequest()
                .getBody()
                .next()
                .flatMap(body -> {
                    try {
                        ObjectMapper mapper = new ObjectMapper();
                        Map<String, String> map = mapper.readValue(body.asInputStream(), new TypeReference<Map<String, String>>() {});

                        return Mono.just(
                                new UsernamePasswordAuthenticationToken(
                                        map.get("username"),
                                        map.get("password")
                                )
                        );

                    } catch (UsernameNotFoundException | IOException e) {
                        e.printStackTrace();
                        return Mono.error(new UsernameNotFoundException("Error while parsing credentials"));
                    }
                });
    }
}